package com.xyhuo.leetcode.december;

import java.util.ArrayList;
import java.util.List;

/**
 * 螺旋矩阵
 * https://leetcode.cn/problems/spiral-matrix/
 *
 * @time 2023/12/22
 */
public class SpiralOrder {

//    public static void main(String[] args) {
//        SpiralOrder so = new SpiralOrder();
////        int[][] matrix = {
////                {1, 2, 3, 4, 13, 14},
////                {19, 20, 21, 22, 23, 24},
////                {25, 26, 27, 28, 29, 30},
////                {5, 6, 7, 8, 15, 16},
////                {9, 10, 11, 12, 17, 18}};
//        int[][] matrix = {
//                {1, 2, 3},
//                {4, 5, 6},
//                {7, 8, 9}
//        };
//        so.spiralOrder(matrix);
//    }

    public List<Integer> spiralOrder(int[][] matrix) {
        this.m = matrix.length;
        this.n = matrix[0].length;
        int min = Math.min(this.m, this.n);
        int cir = min % 2 != 0 ? min / 2 + 1 : min / 2;

        this.already = new int[m][n];
        List<Integer> ans = new ArrayList<>();
        for (int i = 0; i < cir; i++) {
            ringList(ans, matrix, i);
        }
        return ans;
    }

    private int m;
    private int n;

    int[][] already;

    private void ringList(List<Integer> list, int[][] matrix, int index) {
        int min = Math.min(m, n);
        int cir = min % 2 != 0 ? min / 2 : min / 2 - 1;
        if (min % 2 != 0 && index == cir) {
            if (min == m) {
                for (int i = index; i < n - index; i++) {
                    list.add(matrix[index][i]);
                }
            } else {
                for (int i = index; i < m - index; i++) {
                    list.add(matrix[i][index]);
                }
            }
            return;
        }


        int i = index;
        while (true) {
            if (i >= n - index - 1) {
                break;
            }
            list.add(matrix[index][i]);
            i++;
        }

        i = index;
        while (true) {
            if (i >= m - index - 1) {
                break;
            }
            list.add(matrix[i][n - index - 1]);
            i++;
        }

        i = n - index - 1;
        while (true) {
            if (i <= index) {
                break;
            }
            list.add(matrix[m - 1 - index][i]);
            i--;
        }

        i = m - index - 1;
        while (true) {
            if (i <= index) {
                break;
            }
            list.add(matrix[i][index]);
            i--;
        }
    }

}
